/**
 * Created by one on 15-10-23.
 */
var gulp = require('gulp');
var webpack = require('gulp-webpack');
var path = require("path");
var utf8Convert = require('gulp-utf8-convert');
var convertEncoding = require('gulp-convert-encoding');
// var named = require('vinyl-named');
var rev = require('gulp-rev');
var revCollector = require('gulp-rev-collector');
var cleanBuild = require('gulp-clean');
var gulpSequence = require('run-sequence').use(gulp);
// var minifyHTML = require('gulp-minify-html');
var replace = require('gulp-replace');
var fs = require("fs");
var glob = require('glob');
var exec = require('child_process').exec;

var gulpConfig = require('./gulpfile.json');
var webpackConfig = require('./webpackConfig.js');
require('es6-promise').polyfill();


/**
 * webpack js
 */
var args = require('yargs')
    .alias('d', 'debug')
    .alias('pf', 'platform')
    .alias('t', 'targetDir')
    .alias('pa', 'path')//�?�? ??��?��??javascript �? entry.js�?�?  �?:addGoods/  此�????��?��??�??????��?????�????件�?��?? �????缩代???
    .default('debug', false)
    .default('platform', "local")
    .default('targetDir', "")
    .default('pa', '')
    .argv;
var isDebug = args.debug;
var platform = args.platform.toLowerCase();
var targetDir = args.targetDir || gulpConfig.dev.outerFile;
var globalPath = args.pa;
var md5MapPath = path.resolve(targetDir,"md5Map") || gulpConfig.dev.md5MapPath;

// gulp  -d false -pf apitest/outertest/realse --pa
var currPlatFrom = {};
switch (platform) {
    case "localdev":
        currPlatFrom = webpackConfig.LOCALDEV;
        targetDir = path.resolve("../","blueSkyBuild");
        break;
    case "apitest":
        currPlatFrom = webpackConfig.APITESTPARAMS;
        break;
    case "outertest":
        currPlatFrom = webpackConfig.OUTTESTPARAMS;
        break;
    case "realse":
        currPlatFrom = webpackConfig.RELEASEPARAMS;
        break;
    default :
        currPlatFrom = webpackConfig.LOCAL;
        break;
}
gulp.task('default',function() {
    gulpSequence(['webPackJs'],'tplReplaceMd5')
});
gulp.task('webPackJs', function(cb) {
    return gulpSequence(['cleanDir'],['copyTpl'],['copyOtherJs'],['copyCss'],function() {
         glob(gulpConfig.dev.inFile + "/**/entry.js", null, function (err, files) {
            var _compeletFileNum = 0;
            if(files.length == 0) {
                console.log("not find entry.js");
                return;
            }
            return files.map(function (file) {
                var _filePath = path.dirname(file).split("media/")[1];
                var _md5MapFilePath = _filePath.split("javascript/")[1];
                var _config = webpackConfig.webpackConfig;
                _config.entry = {"entry":  file};
                var build = function () {
                        webpack(_config,null,function() {
                            _compeletFileNum++;
                            if (_compeletFileNum == files.length) {
                                cb();
                            }
                        })
                        .pipe(convertEncoding({to: 'utf-8'}))
                        // .pipe(gulpPrefixer('/**** author By gufengpiaoxue@163.com ***/'))
                        .pipe(replace(webpackConfig.MAIN_CDNHOST, currPlatFrom.MAIN_CDNHOST))
                        .pipe(replace(webpackConfig.MAIN_AJAXHOST, currPlatFrom.MAIN_AJAXHOST))
                        .pipe(replace(webpackConfig.MAIN_HOST, currPlatFrom.MAIN_HOST))
                        .pipe(rev())
                        .pipe(gulp.dest(path.resolve(targetDir, "media", _filePath)))
                        .pipe(rev.manifest())
                        .pipe(gulp.dest(path.resolve(md5MapPath, _md5MapFilePath)))
                }
                return build();
            })

        });
    });
});
gulp.task('tplReplaceMd5', function(cb) {
    setTimeout(function() {
        glob(md5MapPath+'/**/*.json',null,function(err,files) {
            files.map(function(file) {
                var opts = {
                    conditionals: true,
                    spare:true
                };
                var baseTargetHtmlPath = path.resolve(targetDir,"tpl",file.split(md5MapPath)[1].split("rev-manifest.json")[0]);
                var targetHtmlPath = path.resolve(targetDir,"tpl")+path.resolve(baseTargetHtmlPath ,"**/*.html");
                function build() {
                    return gulp.src([file, targetHtmlPath])
                        .pipe(revCollector())
                        .pipe(gulp.dest(path.resolve(targetDir,"tpl")+path.resolve(baseTargetHtmlPath)));
                }
                return build();
            });
        });
    },3000);

});
gulp.task('copyCss',['copyImg'], function() {
    var copyCssPath = path.resolve(gulpConfig.dev.inFile,"css/**");
    var copyCssTargetPath = path.resolve(targetDir,"media/css/");
    return gulp.src(copyCssPath)
        .pipe(replace(webpackConfig.MAIN_CDNHOST,currPlatFrom.MAIN_CDNHOST))
        .pipe(gulp.dest(copyCssTargetPath));
});
gulp.task('copyImg', function() {
    var copyImagePath = path.resolve(gulpConfig.dev.inFile,"image/**");
    var copyImageTargetPath = path.resolve(targetDir,"media/image/");
    return gulp.src(copyImagePath,{"read":true})
        .pipe(gulp.dest(copyImageTargetPath));
});
gulp.task('copyOtherJs', function() {
    var copyOtherJsPath = path.resolve(gulpConfig.dev.inFile,"common_lib_3rd/**");
    var copyOtherJsTargetPath = path.resolve(targetDir,"media/common_lib_3rd/");
    return gulp.src(copyOtherJsPath)
        .pipe(gulp.dest(copyOtherJsTargetPath));
});

gulp.task('copyTpl', function() {
    var copyTplPath = path.resolve(gulpConfig.dev.inFile,"../","tpl/**");
    var copyTargetPath = path.resolve(targetDir,"tpl");
    return gulp.src(copyTplPath)
        .pipe(replace(webpackConfig.MAIN_CDNHOST,currPlatFrom.MAIN_CDNHOST))
        .pipe(gulp.dest(copyTargetPath));
});
gulp.task('copySingleHtml',['cleanSingleDir'], function() {
    var copySingleHtmlPath = path.resolve(gulpConfig.dev.inFile,"../","tpl",globalPath+"/**");
    var _buildHtmlPath = path.resolve(targetDir,"tpl",globalPath);
    setTimeout(function() {
        return gulp.src(copySingleHtmlPath)
            .pipe(replace(webpackConfig.MAIN_CDNHOST,currPlatFrom.MAIN_CDNHOST))
            .pipe(gulp.dest(_buildHtmlPath));
    },2000);
});

gulp.task('cleanDir', function() {
    var cleanPath = targetDir;
    return gulp.src(cleanPath)
        .pipe(cleanBuild({force: true}));
});

gulp.task('cleanSingleDir', function(cb) {
    var _cleanJsPath = path.resolve(targetDir,"media","javascript",globalPath,"**");
    var _cleanHtmlPath = path.resolve(targetDir,"tpl",globalPath);
    var _cleanMd5MapPath = path.resolve(targetDir,"md5Map",globalPath);
    gulp.src(_cleanJsPath)
        .pipe(cleanBuild({force: true}));
    gulp.src(_cleanHtmlPath)
        .pipe(cleanBuild({force: true}));
    gulp.src(_cleanMd5MapPath)
        .pipe(cleanBuild({force: true}));
    cb();
});

gulp.task('singleWebPackJs', function() {
    var _config = webpackConfig.webpackConfig;
    var compressSingleJsPath = path.resolve(gulpConfig.dev.inFile,"javascript",globalPath);
    _config.entry = {"entry":  compressSingleJsPath+"/entry.js"};
    var _buildJsPath = path.resolve(targetDir,"media","javascript",globalPath);
    return gulp.src(compressSingleJsPath)
        .pipe(webpack(_config))
        .pipe(convertEncoding({to: 'utf-8'}))
        .pipe(replace(webpackConfig.MAIN_CDNHOST, currPlatFrom.MAIN_CDNHOST))
        .pipe(replace(webpackConfig.MAIN_AJAXHOST, currPlatFrom.MAIN_AJAXHOST))
        .pipe(replace(webpackConfig.MAIN_HOST, currPlatFrom.MAIN_HOST))
        .pipe(gulp.dest(_buildJsPath))
});
gulp.task('singleJs',['copySingleHtml','singleWebPackJs'], function() {
//    var watchSingleEntryPath = path.resolve(gulpConfig.dev.inFile,"javascript",globalPath,"**/*.js");
    var watchSingleEntryPath = path.resolve(gulpConfig.dev.inFile,"javascript","**/*.js");
    var watchSingleHtmlPath = path.resolve(gulpConfig.dev.inFile,"../","tpl",globalPath,"**/*.html");
    var watchSingleEntry = gulp.watch(watchSingleEntryPath,['singleWebPackJs']);
    watchSingleEntry.on('change', function(event) {
        console.log(event.path);
    });
    var watchSingleHtml = gulp.watch(watchSingleHtmlPath,['copySingleHtml']);
    watchSingleHtml.on('change', function(event) {
        console.log(event.path);
    });
});